//
//  OTDR_LF_DrawViewController.m
//  OTDR
//
//  Created by Liu on 2024/6/10.
//

#import "OTDR_LF_DrawViewController.h"
#import "PNChart.h"
#import "BaseNavViewController.h"
#import "AppDelegate.h"
#import "OTDR_TestDetailInfoView.h"
@class PSPDFViewController;

@interface OTDR_LF_DrawViewController ()<PNChartDelegate>
@property (nonatomic, strong) PNLineChart *lineChart;
@property(nonatomic ,strong)NSMutableArray *xDataArray;
@property(nonatomic ,strong)NSMutableArray *yDataArray;
@property(nonatomic ,assign)int yMaxValue;
@property(nonatomic ,assign)int width;//折线图宽
@property(nonatomic ,assign)int height;//折线图高
@property(nonatomic ,assign)int CursorA;
@property(nonatomic ,assign)int CursorB;
@property(nonatomic ,assign)float DisCursorA;
@property(nonatomic ,assign)float DisCursorB;
@property(nonatomic ,assign)float AttAB;
@property(nonatomic ,assign)float LossAB;
@property(nonatomic ,assign)int ZoomXScale;
@property(nonatomic ,assign)int ZoomXScale_Max;
@property(nonatomic ,assign)int ZoomY;
@property(nonatomic ,assign)int Zoom_Y;
/**
 *ab点可变label
 */
@property(nonatomic ,strong)UILabel *ABLabel;
@property(nonatomic ,assign)int CursorPosPointA;
@property(nonatomic ,assign)int CursorPosPointB;

@property (nonatomic, strong)UIScrollView *scrollView;
@property (nonatomic, strong)UIView *bgView;


@property(nonatomic ,assign)NSInteger lf_totalByteCount;
@property(nonatomic ,assign)short lf_HighRE;
@property(nonatomic ,assign)int lf_NumData;
@property(nonatomic ,strong)NSMutableArray *lf_dataF;
@property(nonatomic ,assign)int TotalEvent;
@property(nonatomic ,assign)int TypeEvent;

@property(nonatomic ,strong)NSMutableArray *tableDataArray;
@end


struct DATAEIHEAD {//64+100
    unsigned short   D_Vmode;     //当前曲线的波长代码
    short   D_Vrle;      //量程代码
    short   D_Vatt;      //衰减代码
    short   D_Vpw;       //脉宽值
    int32_t    D_Vzs1310;     //1310群折射率*100000
     int32_t    D_Vzs1550;     //1550群折射率*100000
     int32_t    D_Vzs1625;     //1650或1625群折射率*100000
     int32_t    D_Vzs1490;     //1490群折射率*100000
     int32_t    D_Vzs1383;     //1383群折射率*100000
     int32_t    D_Vzs1300;     //1300群折射率*100000
     int32_t    D_Vzs850;     //850群折射率*100000
     int32_t    D_Vgxue;     //光缆修正系数*100000
    unsigned short  D_V2n;      //实际测试时的平均次数
    unsigned short  D_Avg;     //平均测试模式下设置的平均次数
    unsigned short  D_AvgA;    //自动测试模式下设置的平均次数
    unsigned short  D_Wllm1310;     //1310损耗修正因子*100
    unsigned short  D_Wllm1550;     //1550损耗修正因子*100
    unsigned short  D_Wllm1490;     //1490损耗修正因子 *100
    unsigned short  D_Wllm850;     //850损耗修正因子 *100
    unsigned short  D_Vmodule;   //模块代码
    uint32_t  D_markA;     //光标A在数据组中的位置
    uint32_t  D_markB;     //光标B在数据组中的位置
    uint32_t  D_Orig;     //参考原点在数据组中的位置
    short   D_item;      //测试项目代码
    short   D_TestMode;    //测试模式代码
    short   D_arith;     //测试算法代码
    unsigned short   D_SpAna;    //连接损耗分析事件门限*1000
    unsigned short   D_SpThre;    //连接损耗通过事件门限*1000
    unsigned short   D_RefThre;   //反射损耗通过事件门限*1000
    unsigned short   D_EndThre;   //光纤终点通过事件门限*1000
    uint32_t  D_DTS;  //测试时间
    short   D_Language;  //语言
     int32_t    D_Light;     //检测接入带信号光纤的次数
     int32_t    D_Flage;     //软件标示符
     int32_t    D_Sn;        //本机串号，即机号
     int32_t    D_PWM0;      //LCD屏亮度值
    unsigned short  D_StartMode;   //开机启动的模块，0表示开机进入OTDR模块，1表示开机进入功率计模块。
    unsigned short  D_HighResolution;  //是否是高分辨率测试
    unsigned short D_AutoAna;     //是否在取样后自动分析，0表示不自动分析，1表示取样后自动分析。
    unsigned short D_Lock;       //是否锁定了A、B光标，0表示没有锁定，1表示锁定了A、B光标。
    unsigned short D_Unit;       //长度单位，0表示km,1表示ft,2表示mi。
    unsigned short D_WholeT;     //表示是否处于全程轨迹测试模式，0表示不处于，1表示处于
    unsigned short D_OpmRef;     //光功率值参考值，默认为0dBm
    unsigned short D_OpmZero;    //光功率零点值
    unsigned short D_OpmRan;     //功率计量程代码
    unsigned short D_OpmWave;    //功率计波长代码
    unsigned short D_OpmAvg;     //功率计平均次数
    unsigned short D_WaveSet;    //仪器设置的波长测试代码。(由此代码可知仪器是否是多波长测试，以及设置了那几个波长测试)
     int32_t    D_AutoMode;       //自动模式代码
     int32_t    D_GaShow; //光眼图分析代码
     int32_t    D_AvgTR;      //实际测试时的平均时间
     int32_t    D_AvgT;     //平均测试模式下设置的平均时间
     int32_t    D_AutoSave;
     int32_t    D_Ghost;  //幻峰分析模式代码
     int32_t    D_m7;
     int32_t    D_m8;
     int32_t    D_m9;
//     int32_t    D_m10;
};
struct GenParams{//164
    char     PBID[10];    //GenParams\0
    char     LC[2];          //语言代码
    char     CID[20];         //光缆标识符
    char     FID[20];         //光纤标识符
    unsigned short FT;    //光纤类型，默认为652
    unsigned short NW;    //标称波长
    char     OL[20];          //起点位置
    char     TL[20];          //终点位置
    char     CCD[20];         //光缆代码
    char     CDF[2];         //当前数据标志
    int32_t     UO;          //用户偏置（以100ps为单位表示）
    short     UOD;         //用户偏置（以距离表示）
    char     OP[20];          //操作者
    char     CMT[20];         //评论
 };


struct lastData_def {
    struct DATAEIHEAD FData;
    struct GenParams FGenp;
}lastData;



@implementation OTDR_LF_DrawViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavTitleStr:@""];
    self.view.backgroundColor = kWhiteColor;
    
    
}

- (void )backBtn{
    UIButton *btn = [ViewCreate createButtonFrame:CGRectMake(SCREEN_WIDTH-SIZE(100), SIZE(80), SIZE(80), SIZE(80)) normalBackgroundImage:@"nav_back_icon" selectedBackgroundImage:@"nav_back_icon"];
    [self.view addSubview:btn];
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(SIZE(20));
        make.top.mas_offset(SIZE(45));
        make.width.mas_offset(SIZE(20));
        make.height.mas_offset(SIZE(30));
    }];
    [btn addTarget:self action:@selector(backVC) forControlEvents:UIControlEventTouchUpInside];
}
- (void )backVC{
    [self dismissViewControllerAnimated:NO completion:nil];
}
-(NSMutableArray *)xDataArray{
    if (!_xDataArray) {
        _xDataArray = [NSMutableArray new];
    }
    return _xDataArray;
}
-(NSMutableArray *)yDataArray{
    if (!_yDataArray) {
        _yDataArray = [NSMutableArray new];
    }
    return _yDataArray;
}

- (void)viewWillAppear:(BOOL)animated{
 
    self.navigationController.navigationBar.hidden = YES;
    self.navigationController.tabBarController.tabBar.hidden = YES;
 
    // 强制横屏
    [self forceOrientationLandscape];
 
    BaseNavViewController *nav = (BaseNavViewController *)self.navigationController;
    nav.interfaceOrientation = UIInterfaceOrientationLandscapeRight;
    nav.interfaceOrientationMask = UIInterfaceOrientationMaskLandscapeRight;
 
    //强制翻转屏幕，Home键在右边。
    [[UIDevice currentDevice] setValue:@(UIInterfaceOrientationLandscapeRight) forKey:@"orientation"];
    //刷新
    [UIViewController attemptRotationToDeviceOrientation];
}
 
- (void)viewWillDisappear:(BOOL)animated{
 
    //强制旋转竖屏
    [self forceOrientationPortrait];
    BaseNavViewController *navi = (BaseNavViewController *)self.navigationController;
    navi.interfaceOrientation = UIInterfaceOrientationPortrait;
    navi.interfaceOrientationMask = UIInterfaceOrientationMaskPortrait;
 
    //设置屏幕的转向为竖屏
    [[UIDevice currentDevice] setValue:@(UIDeviceOrientationPortrait) forKey:@"orientation"];
    //刷新
    [UIViewController attemptRotationToDeviceOrientation];
}
#pragma  mark 横屏设置
//强制横屏
- (void)forceOrientationLandscape{
 
    AppDelegate *appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
    appdelegate.isForceLandscape=YES;
    appdelegate.isForcePortrait=NO;
    [appdelegate application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:self.view.window];
}
 
//强制竖屏
- (void)forceOrientationPortrait{
 
    AppDelegate *appdelegate=(AppDelegate *)[UIApplication sharedApplication].delegate;
    appdelegate.isForcePortrait=YES;
    appdelegate.isForceLandscape=NO;
    [appdelegate application:[UIApplication sharedApplication] supportedInterfaceOrientationsForWindow:self.view.window];
}


-(void)setDrawData:(NSData *)drawData{
    _drawData = drawData;
    [self dealDataWithData:drawData];
}


- (void )dealDataWithData:(NSData *)data{
    const int8_t *bytes = [data bytes];
    
    
    char filename_str[15] = {'\0'};
    memcpy(&filename_str, bytes, 14);
    NSLog(@"==========%s",filename_str);
    NSString *fileName = [NSString stringWithFormat:@"%s",filename_str];
    NSString *countStr = [fileName substringFromIndex:4];
    self.lf_totalByteCount = [countStr integerValue];
    NSLog(@"总字节长度：%ld",(long)self.lf_totalByteCount);
    
    short HighRE = 0;
    memcpy(&HighRE, bytes+14, 2);
    self.lf_HighRE = HighRE;
    NSLog(@"%@",HighRE == 0?@"普通分辨率":@"高分辨率");
    
    int NumData = 0;
    memcpy(&NumData, bytes+16, 4);
    NSLog(@"共：%d 个数据点",NumData);
    self.lf_NumData = NumData;
    
    NSMutableArray *lf_dataF = [NSMutableArray array];
    for (int i =20; i < NumData+20; i++) {
        int16_t temp = 0;
        memcpy(&temp, &bytes[2*(i-20)], 2);
        [lf_dataF addObject:@(temp)];
    }
    self.lf_dataF = lf_dataF;
    
    memcpy(&lastData, &bytes[NumData*2+20], sizeof(lastData));
    
    //14+2+4+NumData*2+ 164+164+4+4
    NSInteger lastLength = self.lf_totalByteCount -(2+4+NumData*2+ 168+166);
    NSLog(@"剩余 %ld 字节",(long)lastLength);  // 92
    
    self.TotalEvent = (int )lastLength / 50;
    NSLog(@"TotalEvent:%d",self.TotalEvent);
    
    NSMutableArray *lastData1 = [NSMutableArray array];//+4+4
    for (int i =(14+2+4+NumData*2+ 164+164); i < self.lf_totalByteCount; i++) {
        int8_t temp = 0;
        memcpy(&temp, &bytes[i], 1);
        [lastData1 addObject:[NSString stringWithFormat:@"%02x",temp]];
    }
    
    NSMutableArray *detailInfoArray = [NSMutableArray new];
    
    int index = (2+4+NumData*2+ 168+166);
    
    index += 14;
    
    for (int k=0; k<self.TotalEvent; k++) {
        NSDictionary *infoDic = [NSDictionary new];
        
        index += 18;
        
        short event_style = 0;
        // 这个没处理
        memcpy(&event_style, &bytes[index-2] , 2);
        
        NSLog(@"=============dis_longValue============>%d", index);
        long long dis_longValue = 0;
        for (int i = 0; i < 8; i++) {
            dis_longValue |= ((long long)(bytes[i+index]) & 0xFF) << (i * 8);
        }
        double receevent_Dis= 0;
        memcpy(&receevent_Dis, &dis_longValue , sizeof(double));
        NSLog(@"=============dis_longValue============>%lf", receevent_Dis);
        
        
        index+=8;
        long long ave_longValue = 0;
        for (int i = 0; i < 8; i++) {
            ave_longValue |= ((long long)(bytes[i+index]) & 0xFF) << (i * 8);
        }
        double receevent_Ave= 0;
        memcpy(&receevent_Ave, &ave_longValue , sizeof(double));
        NSLog(@"=============ave_longValue============");

        index+=8;
        long long con_longValue = 0;
        for (int i = 0; i < 8; i++) {
            con_longValue |= ((long long)(bytes[i+index]) & 0xFF) << (i * 8);
        }
        double receevent_Con= 0;
        memcpy(&receevent_Con, &con_longValue , sizeof(double));
        NSLog(@"=============con_longValue============");
        
        
        index+=8;
        long long ref_longValue = 0;
        for (int i = 0; i < 8; i++) {
            ref_longValue |= ((long long)(bytes[i+index]) & 0xFF) << (i * 8);
        }
        double receevent_Ref= 0;
        memcpy(&receevent_Ref, &ref_longValue , sizeof(double));
        NSLog(@"=============ref_longValue============");
        
        
        index+=8;
        long long link_longValue = 0;
        for (int i = 0; i < 8; i++) {
            link_longValue |= ((long long)(bytes[i+index]) & 0xFF) << (i * 8);
        }
        double receevent_link = 0;
        memcpy(&receevent_link, &link_longValue , sizeof(double));
        NSLog(@"=============link_longValue============>%lf", receevent_link);
        
        infoDic = @{
                    @"index":@(k),
                    @"receevent_link":receevent_link ==1.0E7?@"--------":[NSString stringWithFormat:@"%.3f",receevent_link],
                    @"receevent_Ref":receevent_Ref ==1.0E7?@"--------":[NSString stringWithFormat:@"%.3f",receevent_Ref],
                    @"receevent_Con":receevent_Con ==1.0E7?@"--------":[NSString stringWithFormat:@"%.3f",receevent_Con],
                    @"receevent_Ave":receevent_Ave ==1.0E7?@"--------":[NSString stringWithFormat:@"%.3f",receevent_Ave],
                    @"receevent_Dis":[NSString stringWithFormat:@"%.4f",receevent_Dis],
                    @"event_style":@(event_style)
                    };
        [detailInfoArray addObject:infoDic];
    }
    self.tableDataArray = [NSMutableArray new];
    self.tableDataArray = detailInfoArray;
    
   
   
    
    // 获取屏幕对象
    UIScreen *screen = [UIScreen mainScreen];
    // 获取屏幕的宽度和高度
    CGRect screenBounds = screen.bounds;
    CGFloat screenWidth = screenBounds.size.width;
    CGFloat screenHeight = screenBounds.size.height;
    self.width = (screenHeight-self.view.safeAreaInsets.top-self.view.safeAreaInsets.bottom) * screen.scale;
    self.height = screenWidth * screen.scale;
    self.CursorA = ((self.width / 10) + 10)*1.0;
    self.CursorB = ((self.width / 5) + 10)*1.0;
    
    for (int i=0; i<self.width; i++) {
        short value = [self.lf_dataF[i] shortValue];
        if (value > self.yMaxValue) {
            self.yMaxValue = value;
        }
    }
    self.ZoomXScale = self.yMaxValue / ((self.height * 4) / 5);
    if (self.ZoomXScale <= 0) {
        self.ZoomXScale = 1;
    }
    self.ZoomXScale_Max = self.ZoomXScale;
    self.ZoomY = self.lf_NumData / self.width;
    self.Zoom_Y = self.ZoomY;
    
    for (int i=0; i<self.width; i++) {
        [self.yDataArray addObject: self.lf_dataF[self.ZoomY * i]];
        [self.xDataArray addObject:@(i)];
    }
    
    
    //计算初始AB点的值
    int i7 = self.CursorA;//289
    int i8 = self.Zoom_Y;//5
    self.CursorPosPointA = i7 * i8;//1445
    self.CursorPosPointB = self.CursorB * i8;//2845
    float E_dis = [self getEve_Dis];//0.0256
    self.DisCursorA = (self.CursorPosPointA * E_dis) / 1000.0f;//0.037
    self.DisCursorB = (self.CursorPosPointB * E_dis) / 1000.0f;//0.073
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    //创建scrollView  这里设置起始位置的y值为-20是因为状态栏的高度为20  这里是为了实现全屏效果。y设置为0的时候上面的状态栏会有留白。
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_HEIGHT, SCREEN_WIDTH)];
    //设置背景颜色
    self.scrollView.backgroundColor = [UIColor blackColor];
    self.scrollView.contentSize = CGSizeMake(SCREEN_HEIGHT, SCREEN_WIDTH*2+SIZE(10));
    // 设置滚动条  一个是水平滚动条，一个是垂直滚动条
    self.scrollView.showsHorizontalScrollIndicator = YES;
    self.scrollView.showsVerticalScrollIndicator = YES;
    //设置弹簧效果，这个弹簧效果是在滚动到边缘位置时是否有弹动
    self.scrollView.bounces = NO;
    //将scrollView添加到界面上
    [self.view addSubview:self.scrollView];

    
    self.bgView = [ViewCreate createLineFrame:CGRectMake(0, 0,SCREEN_HEIGHT, SCREEN_WIDTH*2+SIZE(10)) backgroundColor:kWhiteColor];
    [self.scrollView addSubview:self.bgView];
    
    
    NSMutableArray *xArr = [NSMutableArray array];
    NSMutableArray *yArr = [NSMutableArray array];
    
    PNLineChart *lineChart=[[PNLineChart alloc]initWithFrame:CGRectMake(self.view.safeAreaInsets.top, 0, SCREEN_HEIGHT-self.view.safeAreaInsets.top-self.view.safeAreaInsets.bottom-SIZE(20), SCREEN_WIDTH)];
    self.lineChart = lineChart;
    lineChart.yValueMax = self.yMaxValue*1.5;
    lineChart.delegate = self;
//    lineChart.axisWidth = 1;
    lineChart.backgroundColor = [UIColor blackColor];
    self.view.backgroundColor = [UIColor blackColor];
    
    // 这里把总数据的长度赋值给 number 根据实际改
    NSInteger number = self.xDataArray.count-1;
    
    int index = 0;
    while (index++ < number) {
        [xArr addObject:self.xDataArray[index]];
    }
    [lineChart setXLabels:xArr];
    
    
    // y的值，赋值到这个数组 根据实际改
    index = 0;
    while (index++<number) {
        [yArr addObject:self.yDataArray[index]];
    }
    
    PNLineChartData*data01=[PNLineChartData new];
    // 线的颜色 根据实际改
    data01.color=[UIColor greenColor];
    data01.itemCount=lineChart.xLabels.count;
    
    data01.getData=^(NSUInteger index){
        CGFloat yValue = [yArr[index] floatValue];
        return [PNLineChartDataItem dataItemWithY:yValue ];
    };
    [self.bgView addSubview:lineChart];
    [self backBtn];
    

    // 三角形的 根据实际改
    NSMutableArray *triangleArr = [NSMutableArray arrayWithCapacity:3];
//    [triangleArr addObject:@(0)];
//    [triangleArr addObject:@(10)];
//    [triangleArr addObject:@(25)];
    self.lineChart.triangleArr = triangleArr;
    self.lineChart.tagColor = [UIColor orangeColor];
    
    // 两条实线 根据实际改
    self.lineChart.solidArr = @[
        @(self.CursorA),
        @(self.CursorB),
    ];
    
    lineChart.chartData=@[data01];
    
    // 画虚线，不需要改
    CGFloat y = 0;
    CGFloat w = SCREEN_HEIGHT-SIZE(20)-self.view.safeAreaInsets.top-self.view.safeAreaInsets.bottom;
    CGFloat h = SCREEN_WIDTH;
    
    CGFloat spaceY = h / 10;
    
    for (int i = 0; i < 11; i++) {
        
        CAShapeLayer *_chartBottomLine = [CAShapeLayer layer];
        _chartBottomLine.lineCap      = kCALineCapButt;
        _chartBottomLine.strokeEnd    = 0.0;
        _chartBottomLine.strokeEnd    = 1.0;
        
        [_chartBottomLine setFillColor:[UIColor clearColor].CGColor];
        //  虚线颜色
        [_chartBottomLine setStrokeColor:[UIColor lightGrayColor].CGColor];
        [_chartBottomLine setLineWidth:0.5];
        [_chartBottomLine setLineJoin:kCALineJoinRound];
        // 间距
        [_chartBottomLine setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:8], [NSNumber numberWithInt:4], nil]];
        _chartBottomLine.strokeColor = [[UIColor lightGrayColor] CGColor];
        
        UIBezierPath *progressline = [UIBezierPath bezierPath];
        [progressline moveToPoint:CGPointMake(0, y)];
        [progressline addLineToPoint:CGPointMake(w, y)];
        
        [progressline setLineWidth:0.5];
        [progressline setLineCapStyle:kCGLineCapSquare];
        _chartBottomLine.path = progressline.CGPath;
        
        [lineChart.layer addSublayer:_chartBottomLine];
        
        y += spaceY;
    }
    
    CGFloat spaceX = w / 10;
    CGFloat lx = 0;
    
    for (int i = 0; i < 11; i++) {
        
        CAShapeLayer *_chartBottomLine = [CAShapeLayer layer];
        _chartBottomLine.lineCap      = kCALineCapButt;
        _chartBottomLine.strokeEnd    = 0.0;
        _chartBottomLine.strokeEnd    = 1.0;
        
        [_chartBottomLine setFillColor:[UIColor clearColor].CGColor];
        [_chartBottomLine setStrokeColor:[UIColor lightGrayColor].CGColor];
        [_chartBottomLine setLineWidth:0.5];
        [_chartBottomLine setLineJoin:kCALineJoinRound];
        // 间距
        [_chartBottomLine setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:8], [NSNumber numberWithInt:4], nil]];
        _chartBottomLine.strokeColor = [[UIColor lightGrayColor] CGColor];
        
        UIBezierPath *progressline = [UIBezierPath bezierPath];
        [progressline moveToPoint:CGPointMake(lx, 0)];
        [progressline addLineToPoint:CGPointMake(lx, h)];
        
        [progressline setLineWidth:0.5];
        [progressline setLineCapStyle:kCGLineCapSquare];
        _chartBottomLine.path = progressline.CGPath;
        
        [lineChart.layer addSublayer:_chartBottomLine];
        
        lx += spaceX;
    }
    
    [lineChart strokeChart];
    
    //  自己改 应该是两个label
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(w-w*0.4*0.5, 10, w*0.4*0.5, h*0.4)];
    label.numberOfLines = 0;
    label.textAlignment = Left;
    label.lineBreakMode = NSLineBreakByWordWrapping;
    label.text = [NSString stringWithFormat:@"%@:%@\n%@:%@\n%@:%@\n%@:%dns\n%@:%ds\n%@:%@ \n%@:%@\n%@:%@",[LanguageTool DPLocalizedString:@"moshi"],lastData.FData.D_AutoMode == 0?[LanguageTool DPLocalizedString:@"zidongmoshi"]:[LanguageTool DPLocalizedString:@"shoudongceshi"],[LanguageTool DPLocalizedString:@"bochang"],[self getwaveDis][0],[LanguageTool DPLocalizedString:@"liangcheng"],[self getVrl],[LanguageTool DPLocalizedString:@"maikuan"],lastData.FData.D_Vpw,[LanguageTool DPLocalizedString:@"pingjunshijian"],lastData.FData.D_AvgTR,[LanguageTool DPLocalizedString:@"zheshelv"],[self getwaveDis][1],[LanguageTool DPLocalizedString:@"shuaijian"],[self getAtt],[LanguageTool DPLocalizedString:@"fenbianlv"],self.lf_HighRE == 0?[LanguageTool DPLocalizedString:@"putongfenbianlv"]:[LanguageTool DPLocalizedString:@"gaofenbianlv"]];
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:13];
    [lineChart addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(0);
        make.top.mas_offset(10);
        make.width.mas_offset(h*0.4);
    }];
    
    self.ABLabel = [[UILabel alloc] initWithFrame:CGRectMake(w*0.6, 10, w*0.4*0.5, h*0.2)];
    self.ABLabel.numberOfLines = 0;
    self.ABLabel.textAlignment = Left;
    self.ABLabel.lineBreakMode = NSLineBreakByWordWrapping;
    
    [self Loss_LSA];
    self.ABLabel.text = [NSString stringWithFormat:@"%@:%.4fkm\n%@:%.4fkm\n%@:%.4fkm\n%@:%.4fdB\n%@:%.4fdB/km",[LanguageTool DPLocalizedString:@"guangbiaoA"],self.DisCursorA,[LanguageTool DPLocalizedString:@"guangbiaoB"],self.DisCursorB,[LanguageTool DPLocalizedString:@"BAjuli"],self.DisCursorB-self.DisCursorA,[LanguageTool DPLocalizedString:@"BAhaosun"],self.LossAB,[LanguageTool DPLocalizedString:@"pingjunsunhao"],self.AttAB];
;
    self.ABLabel.textColor = [UIColor whiteColor];
    self.ABLabel.font = [UIFont systemFontOfSize:13];
    [lineChart addSubview:self.ABLabel];
    [self.ABLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(label.mas_left).mas_offset(0);
        make.top.mas_offset(10);
        make.width.mas_offset(h*0.4);
    }];
    
    
    OTDR_TestDetailInfoView *detailInfoView = [[OTDR_TestDetailInfoView alloc] initWithFrame:CGRectMake(0, SCREEN_WIDTH+SIZE(10), SCREEN_HEIGHT, SCREEN_WIDTH)];
    detailInfoView.tableDataArray = self.tableDataArray;
    [self.bgView addSubview:detailInfoView];
    [detailInfoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_offset(0);
        make.top.mas_equalTo(self.lineChart.mas_bottom).mas_offset(0);
    }];
    
    
    UIButton *downLoadPDFBtn = [ViewCreate createButtonFrame:CGRectMake(SCREEN_HEIGHT-[UIApplication sharedApplication].keyWindow.safeAreaInsets.bottom-SIZE(100), SCREEN_WIDTH*2-SIZE(150), SIZE(35), SIZE(35)) normalBackgroundImage:@"cana" selectedBackgroundImage:@"cana"];
    [self.scrollView addSubview:downLoadPDFBtn];
    [downLoadPDFBtn addTarget:self action:@selector(downLoadPDF) forControlEvents:UIControlEventTouchUpInside];
}
- (void )downLoadPDF{
    NSString *tiemStamp = [NSString stringWithFormat:@"%@",[LLUtils dateStrWithDate:[NSDate date] dateFormat:@"yyyyMMddHHmmss"]];
    [self generatePDFFromView:self.bgView withFileName:tiemStamp];
}



//获取衰减值
- (NSString *)getAtt{
    NSString *att = @"0dB";
    switch (lastData.FData.D_Vatt) {
        case 0:
            att = @"0dB";
            break;
        case 1:
            att = @"5dB";
            break;
        case 2:
            att = @"10dB";
            break;
        case 3:
            att = @"15dB";
            break;
        case 4:
            att = @"20dB";
            break;
        default:
            att = @"0dB";
            break;
    }
    return att;
}

//获取量程
- ( NSString * )getVrl{
    NSString  *vrle = @"0.0km";
    switch (lastData.FData.D_Vrle) {
        case 0:
            vrle = @"400m";
            break;
        case 1:
            vrle = @"800m";
            break;
        case 2:
            vrle = @"1.6km";
            break;
        case 3:
            vrle = @"3.2km";
            break;
        case 4:
            vrle = @"8km";
            break;
        case 5:
            vrle = @"16km";
            break;
        case 6:
            vrle = @"32km";
            break;
        case 7:
            vrle = @"64km";
            break;
        case 8:
            vrle = @"128km";
            break;
        case 9:
            vrle = @"256km";
            break;
        case 10:
            vrle = @"512km";
            break;
        default:
            vrle = @"0.0km";
            break;
    }
    return vrle;
}

//获取波长,折射率
- (NSArray *)getwaveDis{
    short s = lastData.FData.D_Vmode;
    NSArray *wave = @[@"1300nm",[NSString stringWithFormat:@"%d",lastData.FData.D_Vzs1300]];
    if (s == 4) {
        wave = @[@"1625nm",[NSString stringWithFormat:@"%d",lastData.FData.D_Vzs1625]];
    } else if (s == 8) {
        wave = @[@"1650nm",[NSString stringWithFormat:@"%d",lastData.FData.D_Vzs1625]];
    } else if (s == 16) {
        wave = @[@"1490nm",[NSString stringWithFormat:@"%d",lastData.FData.D_Vzs1490]];
    } else if (s == 32) {
        wave = @[@"850nm",[NSString stringWithFormat:@"%d",lastData.FData.D_Vzs850]];
    } else if (s != 64) {
        switch (s) {
            case 1:
                wave = @[@"1310nm",[NSString stringWithFormat:@"%d",lastData.FData.D_Vzs1310]];
                break;
            case 2:
                wave = @[@"1550nm",[NSString stringWithFormat:@"%d",lastData.FData.D_Vzs1550]];
                break;
            default:
                wave = @[@"1310nm",[NSString stringWithFormat:@"%d",lastData.FData.D_Vzs1310]];
                break;
        }
    } else {
        wave = @[@"1300nm",[NSString stringWithFormat:@"%d",lastData.FData.D_Vzs1300]];
    }
    return wave;
}


- (float )getEve_Dis{
   float f;
   short s = lastData.FData.D_Vmode;
   if (s == 4 || s == 8) {
       f = lastData.FData.D_Vzs1625;
   } else if (s == 16) {
       f = lastData.FData.D_Vzs1490;
   } else if (s == 32) {
       f = lastData.FData.D_Vzs850;
   } else if (s == 64) {
       f = lastData.FData.D_Vzs1300;
   } else if (s != 128) {
       switch (s) {
           case 1:
               f = lastData.FData.D_Vzs1310;
               break;
           case 2:
               f = lastData.FData.D_Vzs1550;
               break;
           default:
               f = lastData.FData.D_Vzs1310;
               break;
       }
   } else {
       f = lastData.FData.D_Vzs1383;
   }
   double d = f;
   f = (d < 1.0 || d > 2.0) ? 1.46f : 1.46f;
   float f2 = 20.0f;
   switch (lastData.FData.D_Vrle) {
       case 0:
           f2 = 0.25f;
           break;
       case 1:
           f2 = 0.5f;
           break;
       case 2:
           f2 = 1.0f;
           break;
       case 3:
           f2 = 2.0f;
           break;
       case 4:
           f2 = 5.0f;
           break;
       case 5:
           f2 = 10.0f;
           break;
       case 7:
           f2 = 40.0f;
           break;
       case 8:
           f2 = 80.0f;
           break;
       case 9:
           f2 = 160.0f;
           break;
       case 10:
           f2 = 320.0f;
           break;
   }
   return ((f2 * 14990.0f) / (f * 100000.0f)) / (self.lf_NumData / 16384.0f);
}



-(void )Loss_LSA{
    int i;
    int i2 = self.CursorPosPointA;
    int i3 = self.CursorPosPointB;
    float f = 0.0f;
    if (i2 < i3 && i2 <= (i = self.lf_NumData) && i3 <= i && i2 >= 0) {
        double d = (i3 - i2) + 1;
        double d2 = 0.0;
        double d3 = 0.0;
        double d4 = 0.0;
        double d5 = 0.0;
        while (i2 <= self.CursorPosPointB) {
            double d6 = [self.lf_dataF[i2] doubleValue];
            d4 += d6;
            double d7 = i2;
            d3 += d7;
            d5 += d6 * d7;
            d2 += d7 * d7;
            i2++;
        }
        double d8 = [self getEve_Dis];
        double d9 = ((d2 * d) - (d3 * d3)) * d8;
        double d10 = lastData.FData.D_Vgxue;
        double d11 = d9 * d10;
        if (d11 == 0.0) {
            d11 = 0.01;
        }
        f = (float) (((d * d5) - (d3 * d4)) / d11);
        double d12 = [self.lf_dataF[self.CursorPosPointA] doubleValue] - [self.lf_dataF[self.CursorPosPointB] doubleValue];
        self.LossAB = (float) (d12 * 0.001);
    } else {
        self.LossAB = 0.0f;
    }
    self.AttAB = (-f) * [self CurrentWllm];
}

-(float )CurrentWllm{
    short s = lastData.FData.D_Vmode;
    if (s != 4) {
        if (s == 8) {
            short s2 = lastData.FData.D_Vmodule;
            if (s2 == 4105 || s2 == 4104) {
                return lastData.FData.D_Wllm850;
            }
            return lastData.FData.D_Wllm1490;
        } else if (s == 16) {
            short s3 = lastData.FData.D_Vmodule;
            if (s3 == 4101 || s3 == 4103) {
                return lastData.FData.D_Wllm850;
            }
            return lastData.FData.D_Wllm1490;
        } else if (s != 32) {
            if (s != 64) {
                if (s == 128) {
                    return lastData.FData.D_Vmodule == 4102 ? lastData.FData.D_Wllm850 : lastData.FData.D_Wllm1490;
                }
                switch (s) {
                    case 1:
                        return lastData.FData.D_Wllm1310;
                    case 2:
                        return lastData.FData.D_Wllm1550;
                    default:
                        return lastData.FData.D_Wllm1310;
                }
            }
            return lastData.FData.D_Wllm1490;
        } else {
            return lastData.FData.D_Wllm850;
        }
    }
    return lastData.FData.D_Wllm1490;
}


//绘图回调
- (void)aIndex:(NSInteger)aIndex bIndex:(NSInteger)bIndex {
    NSLog(@"回调A点位置-----=%@,回调B点位置-----%@", @(aIndex), @(bIndex));
    // 在这里刷新有上角的数据
    //计算初始AB点的值
    if (aIndex>-1) {
        self.CursorA = aIndex*1.0;
    }
    if (bIndex>-1) {
        self.CursorB = bIndex*1.0;
    }
    int i7 = self.CursorA;//31
    int i8 = self.Zoom_Y;//5
    self.CursorPosPointA = i7 * i8;//155
    self.CursorPosPointB = self.CursorB * i8;//355
    float E_dis = [self getEve_Dis];
    self.DisCursorA = (self.CursorPosPointA * E_dis) / 1000.0f;
    self.DisCursorB = (self.CursorPosPointB * E_dis) / 1000.0f;
    [self Loss_LSA];
    self.ABLabel.text = [NSString stringWithFormat:@"%@:%.4fkm\n%@:%.4fkm\n%@:%.4fkm\n%@:%.4fdB\n%@:%.4fdB/km",[LanguageTool DPLocalizedString:@"guangbiaoA"],self.DisCursorA,[LanguageTool DPLocalizedString:@"guangbiaoB"],self.DisCursorB,[LanguageTool DPLocalizedString:@"BAjuli"],self.DisCursorB-self.DisCursorA,[LanguageTool DPLocalizedString:@"BAhaosun"],self.LossAB,[LanguageTool DPLocalizedString:@"pingjunsunhao"],self.AttAB];
}
- (void)userClickedOnLineKeyPoint:(CGPoint)point lineIndex:(NSInteger)lineIndex pointIndex:(NSInteger)pointIndex{
    
}




//绘制PDF
- (void)generatePDFFromView:(UIView *)view withFileName:(NSString *)fileName {
    NSMutableData *pdfData = [NSMutableData data];
    UIGraphicsBeginPDFContextToData(pdfData, view.frame, nil);

    CGContextRef pdfContext = UIGraphicsGetCurrentContext();

    UIGraphicsBeginPDFPage();

    [view.layer renderInContext:pdfContext];

    UIGraphicsEndPDFContext();

    NSString*documentsPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSFileManager *fileManager      = [NSFileManager defaultManager];
    NSString      *testDirectory    = [documentsPath stringByAppendingPathComponent:@"PDFFile"];
    
    BOOL isExists = [fileManager fileExistsAtPath:testDirectory];
//    if (isExists) {
//        return;
//    }
    // 创建目录
    BOOL res=[fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    if (res) {
        NSLog(@"文件夹创建成功");
    }else{
        NSLog(@"文件夹创建失败");
    }
    
    // 保存 PDF 文件
    NSString      *pdfDirectory = [documentsPath stringByAppendingPathComponent:@"PDFFile"];
    NSString *filePath = [pdfDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.pdf", fileName]];
    BOOL isOK = [pdfData writeToFile:filePath atomically:YES];
    if (!isOK) {
        [ToastView tip:[LanguageTool DPLocalizedString:@"baocunpdfshibai"]];
    }else{
        [ToastView tip:[LanguageTool DPLocalizedString:@"baocunpdfchenggong"]];
    }
}
@end
